package com.wondertek.web.controller.sys;


import cn.hutool.core.io.IoUtil;
import com.wondertek.common.base.Result;

import com.wondertek.service.dto.sys.req.SysUploadByUrlReq;
import com.wondertek.service.entity.sys.SysFilePo;
import com.wondertek.service.service.sys.ISysFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author xqs
 */
@RestController
@RequestMapping("/backend/sys/file")
@Tag(name = "系统文件管理")
@CrossOrigin("*")
public class SysFileController {

    @Resource
    private ISysFileService sysFileService;

    /*
    * 单个查询文件
    * */
    @GetMapping("/get")
    @Operation(summary = "单个查询文件")
    public Result<SysFilePo> emailCode(@RequestParam(name="id") String id){
        return Result.success(sysFileService.getById(id));
    }

    /**
     * 单个文件上传
     */
    @PostMapping("/upload")
    @Operation(summary = "单个文件上传")
    public Result<SysFilePo> upload(@RequestPart("file") MultipartFile file, HttpServletRequest request){
        SysFilePo filePo = sysFileService.upload(file);
        return Result.success(filePo);
    }

    /**
     * 批量文件上传
     */
    @PostMapping(value = "uploadBatch",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "批量文件上传")
    public Result<List<SysFilePo>> uploadBatch(@RequestPart("files") MultipartFile[] files, HttpServletRequest request){
        List<SysFilePo>  filePos = sysFileService.uploadBatch(files);
        return Result.success(filePos);
    }

    /**
     * url上传
     */
    @PostMapping("/uploadByUrl")
    @Operation(summary = "url拉取上传")
    public Result<SysFilePo> uploadByUrl(@RequestBody @Validated SysUploadByUrlReq sysUploadByUrlReq){
        SysFilePo filePo = sysFileService.uploadByUrl(sysUploadByUrlReq);
        return Result.success(filePo);
    }

    /**
     * 预览文件
     */
    @Operation(summary = "预览文件")
    @GetMapping("/viewFile/{fileName}")
    public void viewFile(HttpServletRequest request, HttpServletResponse response,
                         @PathVariable String fileName) throws IOException {
        SysFilePo sysFilePo = sysFileService.lambdaQuery().eq(SysFilePo::getFileName, fileName).one();
        File file = new File(sysFilePo.getFilePath());
        if(!file.exists()){
            response.setStatus(404);
            return;
        }
        // 预览
        response.setHeader("Content-Disposition", "inline; filename*=" + fileName);
        IoUtil.write(response.getOutputStream(),false,IoUtil.readBytes(new FileInputStream(file)));
        response.getOutputStream().flush();
    }

    /**
     * 下载文件
     */
    @Operation(summary = "下载文件")
    @GetMapping("/downloadFile/{fileName}")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable String fileName) throws IOException {
        SysFilePo sysFilePo = sysFileService.lambdaQuery().eq(SysFilePo::getFileName, fileName).one();
        File file = new File(sysFilePo.getFilePath());
        if(!file.exists()){
            response.setStatus(404);
            return;
        }
        // 下载
        // 这里URLEncoder.encode可以防止中文乱码
        fileName = URLEncoder.encode(sysFilePo.getOriginalFilename(),
                StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName);
        response.setContentType("multipart/form-data");
        IoUtil.write(response.getOutputStream(),false,IoUtil.readBytes(new FileInputStream(file)));
        response.getOutputStream().flush();
    }

    /**
     * 下载文件
     */
    @Operation(summary = "删除文件")
    @GetMapping("/delete/{id}")
    public Result<?>  deleteFile(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable String id) throws IOException {
        sysFileService.removeById(id);
        return Result.success();
    }

}
